package com.java.coustomer.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

/**
 * 智能机器人接口
 */
public class GetRobotConent {


    /**
     * 获取访问链接的源码
     * @param link 访问网址
     * @return java.lang.String
     */
    public static String getContent(String link){
        //访问api接口
        String text = null;

        StringBuilder sb = new StringBuilder();
        try {
            //1.建立网络链接
            URL url = new URL(link);
            //2.打开网络链接
            URLConnection uc = url.openConnection();
            //3.读取内容 创建文件输入流
            InputStream inputStream = uc.getInputStream();
            //stream转化为reader
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

            //4.创建缓冲流
            BufferedReader bf = new BufferedReader(inputStreamReader);
            //5.正式读取内容
            while((text=bf.readLine())!=null){
                //将每次读取到的内容保存到StringBuilder中
                sb.append(text);
            }

            //关闭流
            bf.close();
            inputStreamReader.close();
            inputStream.close();


        } catch (MalformedURLException e) {
            System.out.println("您访问的网页不存在，请检查访问地址");
            throw new RuntimeException(e);
        } catch (IOException e) {
            System.out.println("世界上最遥远的距离就是没有网");
            throw new RuntimeException(e);
        }

        return sb.toString();
    }

    public static void main(String[] args) {


        while (true){
            Scanner scanner = new Scanner(System.in);
            String read = scanner.nextLine();

            String content = getContent("http://api.qingyunke.com/api.php?key=free&appid=0&msg="+read);
            //解析数据
            JSONObject jsonObject = JSON.parseObject(content);
            String massage = jsonObject.getString("content");
            System.out.println(massage);
        }
    }
}
